<template>    
    <div>
        <el-input :placeholder="placeholder" :readonly="true" v-model="address">
            <el-button slot="append" icon="el-icon-location-outline" @click="show=true"></el-button>
        </el-input>
        <el-dialog
        title="地址选择"
        top="5vh"
        :modal="false"
        :visible.sync="show"
        width="80%">
        <div style="width:100%;height:80%;">
          <iframe class="map-item" id="getAddress" @load="loadiframe" :height="height"
                  :src="'https://m.amap.com/picker/?key=11f4af50456e0e66da3e26f76a29596e&center='+(this.center?this.center:'')"
                  style="width:100%;display: block; height: 80vh;"></iframe>
        </div>
        </el-dialog>

        <el-dialog
          title="确认地址"
          :visible.sync="dialogVisible"
          width="400px">
          <span>{{addressName}}</span>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmAddress">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
  import { getAddrByLngLat } from '@/utils/location'

  export default {
    props: ["placeholder","height", "address", "center"],
    data() {
      return {
        show: false,
        dialogVisible: false,
        addressName:'',
        lnglat:''
      }
    },
    created() {

    },
    methods: {
      loadiframe() {
        let iframe = document.getElementById('getAddress').contentWindow;
        iframe.postMessage('hello', 'https://m.amap.com/picker/');
        window.addEventListener("message", function (e) {
          if (e.data.command != "COMMAND_GET_TITLE") {
            if(e.data.name) {
              var that = this;
              that.addressName = e.data.name;
              that.lnglat = e.data.location;

              that.dialogVisible = true;              
            }
          }
        }.bind(this), false);
      },
      confirmAddress(){
        var that = this;
        getAddrByLngLat(that.lnglat.split(","), function(addr) {
          that.show = false;
          that.dialogVisible = false;    
          addr.lnglat = that.lnglat;
          addr.name = that.addressName;
          that.$emit("addressPicked", addr);
        });
      }
    }
  }
</script>
<style>
  .map-item {
    /* width: 100%;
    height: 100%; */
    top: 0;
    background: #fff;
  }
  .modal {
      position: fixed;
      top: 50px;
      width: 500px;
  }
</style>